package com.bitdf.txing.group.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bitdf.txing.common.interceptor.LoginInterceptor;
import com.bitdf.txing.common.to.UserTo;
import com.bitdf.txing.common.utils.PageUtils;
import com.bitdf.txing.common.utils.R;
import com.bitdf.txing.common.vo.UserInfoVo;
import com.bitdf.txing.group.constant.RedisConstant;
import com.bitdf.txing.group.dao.GroupCommentDao;
import com.bitdf.txing.group.entity.GroupCommentEntity;
import com.bitdf.txing.group.feign.EsFeignService;
import com.bitdf.txing.group.service.GroupCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.stream.Collectors;

/**
 * 评论相关service
 *
 * @author Li zhiwei
 */
@Service("groupCommentService")
public class GroupCommentServiceImpl extends ServiceImpl<GroupCommentDao, GroupCommentEntity> implements GroupCommentService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    EsFeignService esFeignService;

    /**
     * 查询评论
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        long groupId;
        try {
            groupId = Integer.parseInt((String) params.get("groupId"));
        } catch (NumberFormatException e) {
            return null;
        }
        //获取评论
        BoundListOperations<String, String> ops = stringRedisTemplate.opsForList().getOperations().boundListOps(RedisConstant.GROUP_COMMENT_NAME + groupId + ":content");
        List<String> list;
        //默认获取第一页的评论，每页15条记录
        int limit = 15;
        int page = 1;
        PageUtils pageUtils;

        try {
            page = Integer.parseInt((String) params.get("page"));
            limit = Integer.parseInt((String) params.get("limit"));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        //先查询redis
//        String index = ops.index(0);
        list = ops.range(limit * (page - 1), limit * (page - 1) + limit);
        if (list != null && list.size() > 0) {
            List<GroupCommentEntity> list1 = list.stream().map((s) -> {
                GroupCommentEntity entity = JSON.parseObject(s, GroupCommentEntity.class);
                return entity;
            }).collect(Collectors.toList());
            //查询评论总数
            String count = stringRedisTemplate.opsForValue().get(RedisConstant.GROUP_COMMENT_NAME + params.get("groupId") + ":totalCount");
            pageUtils = new PageUtils(list1, Integer.parseInt(count), limit, page);
        } else {
            //若redis中没有，则查询数据库
            IPage<GroupCommentEntity> page1 = null;
//                    this.page(
//                    new Query<GroupCommentEntity>().getPage(params),
//                    new QueryWrapper<GroupCommentEntity>()
//            );
            pageUtils = new PageUtils(page1);
        }
        return pageUtils;
    }

    /**
     * 添加组团评论
     *
     * @param groupId
     * @param content
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean commentGroup(Long groupId, String content) {
        // 获取真正评论用户
        UserInfoVo userInfoVo = (UserInfoVo) StpUtil.getSession().get("user");
        //保存到数据库
        Date date = new Date();
//        GroupCommentEntity commentEntity = new GroupCommentEntity(null, groupId, content, date, userTo.getId(), 0);
        GroupCommentEntity commentEntity = new GroupCommentEntity(groupId, content, userInfoVo.getId(), 0);
        boolean save = this.save(commentEntity);

        GroupCommentEntity entity = this.getById(commentEntity.getId());
        //缓存到redis
        BoundListOperations<String, String> ops = stringRedisTemplate.opsForList().getOperations().boundListOps(RedisConstant.GROUP_COMMENT_NAME + groupId + ":content");
        BoundValueOperations<String, String> opsCount = stringRedisTemplate.opsForValue().getOperations().boundValueOps(RedisConstant.GROUP_COMMENT_NAME + groupId + ":totalCount");
        JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai");
        String s = JSON.toJSONString(entity);
        if (ops.leftPush(s) == -1) {
            return false;
        }
        opsCount.increment();
        //只缓存最新的一百条评论
        ops.trim(0, 100);
        //更新es中的组团数据，使评论数+1
        R r = esFeignService.countIncreOrDcre(groupId, 1, "commentCount");
        return r.getCode() == 200 ? true : false;
    }

    /**
     * 删除评论
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByIds1(Integer id) {

        JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai");
        //删除数据库数据
        GroupCommentDao commentDao = this.baseMapper;
        GroupCommentEntity entity = this.getById(id);
        int i = commentDao.deleteById(id);
        //删除与更新redis中数据
        BoundListOperations<String, String> ops = stringRedisTemplate.opsForList().getOperations().boundListOps(RedisConstant.GROUP_COMMENT_NAME + entity.getGroupId() + ":content");
        try {
            Long remove = ops.remove(1, JSON.toJSONString(entity));
            Long decrement = stringRedisTemplate.opsForValue().decrement(RedisConstant.GROUP_COMMENT_NAME + entity.getGroupId() + ":totalCount");
            //更新es中的组团数据，使评论数-1
            R r = esFeignService.countIncreOrDcre(entity.getGroupId(), -1, "commentCount");
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}